package com.it.homework;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author げっしょく
 * @date 2021/8/7
 */
public class Test1 {
    public static void main(String[] args) {
        /*
        1. 用lock锁解决线程安全
         */
        Thread t1 = new Ticket();
        Thread t2 = new Ticket();
        t1.setName("窗口一");
        t2.setName("窗口二");
        t1.start();
        t2.start();
    }
}


class Ticket extends Thread{
    private static int sun = 100;
    private static Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if(sun == 0){
                    break;
                }else {
                    sun--;
                    System.out.println(Thread.currentThread().getName() + "正在卖票； 现在还剩" + sun + "张票");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
